//
//  JKNewsListGetDataModel.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/5.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit

class JKNewsListGetDataModel: NSObject {
    
    /** 加载首页最新数据 */
    public class func loadLatestData(finishedBlock: @escaping ((_ dict: NSDictionary?, _ error: Error?) -> ())) {
        
        // 从本地获取最新数据
        var dateStr = String() // 日期
        var topStoryDicts = [[String : AnyObject]]() // 5条热门文章字典数组
        var latestStoryDicts = [[String : AnyObject]]() // 今日最新文章字典数组
        var storieModels = [JKNewsListModel]() // 今日最新文章模型数组
        
        var resultDict : [String : AnyObject] = [String : AnyObject]() /* [JKStoryDateKey : "" as AnyObject,
                                                 JKStoryListModelKey : [JKNewsListModel]() as AnyObject,
                                                 JKTopStoryListKey : [[String : AnyObject]]() as AnyObject,
                                                 JKStoryFmtDateKey : "" as AnyObject] */
        
        if let dict = JKSQLiteManager.queryLatestStoryList() {
            
            dateStr = dict[JKStoryDateKey] as! String
            latestStoryDicts = dict[JKStoryListDictKey] as! [[String : AnyObject]]
            topStoryDicts = dict[JKTopStoryListKey] as! [[String : AnyObject]]
            
            if let newsListModels = [JKNewsListModel].deserialize(from: latestStoryDicts) {
                
                storieModels = newsListModels as! [JKNewsListModel]
                
                resultDict[JKStoryDateKey] = dateStr as AnyObject
                
                resultDict[JKStoryListModelKey] = storieModels as AnyObject
                
                resultDict[JKTopStoryListKey] = topStoryDicts as AnyObject
                
                var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: dateStr + "000101"), format: "MM月dd日")
                fmtDate += " "
                fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: dateStr))
                
                resultDict[JKStoryFmtDateKey] = fmtDate as AnyObject
            }
            
            // 仅在网络不可用时才真正加载本地数据，因为首页数据会一直变化
            if (JKSQLiteManager.shared.reach.currentReachabilityStatus() == NotReachable) {
                
                JKProgressHUD.showError(withStatus: "您的网络貌似有点问题~~")
                
                finishedBlock(resultDict as NSDictionary, nil)
                
                return
            }
        }
        
        
        // 从网络加载最新数据
        JKNetworkingTool.shared.requestGet(url: "news/latest", parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                finishedBlock(resultDict as NSDictionary, error)
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                finishedBlock(resultDict as NSDictionary, JKBaseError(desc: "未获取到数据"))
                
                return
            }
            
            var dict = [String : AnyObject]()
            
            guard let date = (json["date"]) as? String else {
                
                finishedBlock(resultDict as NSDictionary, JKBaseError(desc: "未获取到日期数据"))
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                finishedBlock(resultDict as NSDictionary, JKBaseError(desc: "未获取到最新文章数据"))
                
                return
            }
            
            // 缓存最新文章列表
            JKSQLiteManager.cacheStoryLists(stories: stories, date: date, isTop: false, isLatest: true, isMore: false)
            
            guard let top_stories = (json["top_stories"]) as? [[String : AnyObject]] else {
                
                finishedBlock(resultDict as NSDictionary, JKBaseError(desc: "未获取到热门文章数据"))
                
                return
            }
            
            // 缓存5条热门列表
            JKSQLiteManager.cacheTopStories(topStories: top_stories, date: date)
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                finishedBlock(resultDict as NSDictionary, JKBaseError(desc: "最新文章转模型失败"))
                
                return
            }
            
            // 日期
            dict[JKStoryDateKey] = date as AnyObject
            
            var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: date + "000101"), format: "MM月dd日")
            fmtDate += " "
            fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: date))
            
            dict[JKStoryFmtDateKey] = fmtDate as AnyObject
            
            // 最新文章列表
            dict[JKStoryListModelKey] = newsListModels as AnyObject
            dict[JKStoryListDictKey] = stories as AnyObject
            
            // 5条热门文章
            dict[JKTopStoryListKey] = top_stories as AnyObject
            /*
             if let top_storyModels = [JKNewsListModel].deserialize(from: top_stories) {
             
             dict[JKTopStoryListKey] = top_storyModels as AnyObject
             } */
            
            finishedBlock(dict as NSDictionary, nil)
        }
    }
    
    /** 加载首页更多数据 */
    public class func loadMoreDataWithDate(date: String, finishedBlock: @escaping ((_ dict: NSDictionary?, _ error: Error?) -> ())) {
        
        let beforeDate = JKDateTool.getPreviousDayOfSpecifiedDate(date: date)
        
        if let listsDict = JKSQLiteManager.queryStoryListWithDate(date: beforeDate) {
            
            let lists = listsDict[JKStoryListDictKey] as! [[String : AnyObject]]
            let dateStr = listsDict[JKStoryDateKey] as! String
            
            if let newsListModels = [JKNewsListModel].deserialize(from: lists) {
                
                var resultDict = [String : AnyObject]()
                
                resultDict[JKStoryDateKey] = dateStr as AnyObject
                
                resultDict[JKStoryListModelKey] = newsListModels as AnyObject
                
                var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: dateStr + "000101"), format: "MM月dd日")
                fmtDate += " "
                fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: dateStr))
                
                resultDict[JKStoryFmtDateKey] = fmtDate as AnyObject
                
                if (lists.count > 1) {
                    
                    finishedBlock(resultDict as NSDictionary, nil)
                    
                    return
                }
            }
        }
        
        // 数据库没有取得数据，从网络请求数据
        JKNetworkingTool.shared.requestGet(url: "news/before/" + date, parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                finishedBlock(nil, error)
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到数据"))
                
                return
            }
            
            var dict = [String : AnyObject]()
            
            guard let date = (json["date"]) as? String else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到日期数据"))
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到文章数据"))
                
                return
            }
            
            // 执行缓存
            JKSQLiteManager.cacheStoryLists(stories: stories, date: date, isTop: false, isLatest: false, isMore: true)
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                finishedBlock(nil, JKBaseError(desc: "文章转模型失败"))
                
                return
            }
            
            // 日期
            dict[JKStoryDateKey] = date as AnyObject
            
            var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: date + "000101"), format: "MM月dd日")
            fmtDate += " "
            fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: date))
            
            dict[JKStoryFmtDateKey] = fmtDate as AnyObject
            
            dict[JKStoryListModelKey] = newsListModels as AnyObject
            
            dict[JKStoryListDictKey] = stories as AnyObject
            
            finishedBlock(dict as NSDictionary, nil)
        }
    }
    
    
    /** 加载新闻详情数据 */
    public class func loadDetailDataWithID(ID: String, detailBlock: @escaping ((_ detailModel: JKNewsDetailModel?, _ json: [String : AnyObject]?, _ error: Error?) -> ()), extraBlock: ((_ extraModel: JKNewsDetailExtraModel?, _ error: Error?) -> ())?) {
        
        if extraBlock != nil {
            
            // 获取详情扩展数据 评论条数  （扩展数据变化较快，所以不缓存了）
            JKNetworkingTool.shared.requestGet(url: "story-extra/" + ID, parameters: nil) { (responseJson, error) in
                
                if error != nil {
                    
                    extraBlock!(nil, error)
                    
                    return
                }
                
                guard let json = responseJson as? [String : AnyObject] else {
                    
                    extraBlock!(nil, JKBaseError(desc: "未获取到数据"))
                    
                    return
                }
                
                guard let extraModel = JKNewsDetailExtraModel.deserialize(from: json) else {
                    
                    extraBlock!(nil, JKBaseError(desc: "数据序列化错误"))
                    
                    return
                }
                
                extraBlock!(extraModel, nil)
            }
        }
        
        // 从本地获取详情数据
        if let detailDict = JKSQLiteManager.queryStoryDetailWithID(ID: ID) {
            
            if let detailModel = JKNewsDetailModel.deserialize(from: detailDict)  {
                
                detailBlock(detailModel, detailDict, nil)
                
                return
            }
        }
        
        // 没有从本地获取到详情数据，从网络加载
        JKNetworkingTool.shared.requestGet(url: "news/" + ID, parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                detailBlock(nil, nil, error)
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                detailBlock(nil, nil, JKBaseError(desc: "未获取到数据"))
                
                return
            }
            
            // 执行缓存
            JKSQLiteManager.cacheDetail(detailDict: json, ID: ID, justCache: false)
            
            guard let detailModel = JKNewsDetailModel.deserialize(from: json) else {
                
                detailBlock(nil, nil, JKBaseError(desc: "数据转模型错误"))
                
                return
            }
            
            detailBlock(detailModel, json, nil)
        }
    }
    
    // MARK: - 其它主题 暂不可用
    
    /** 加载首页最新数据 */
    public class func loadOtherThemeLatestData(finishedBlock: @escaping ((_ dict: NSDictionary?, _ error: Error?) -> ())) {
        
        // 从本地获取最新数据
        var dateStr = String() // 日期
        var latestStoryDicts = [[String : AnyObject]]() // 文章字典数组
        var storieModels = [JKNewsListModel]() // 文章模型数组
        
        var resultDict = [String : AnyObject]()
        
        if let dict = JKSQLiteManager.queryLatestStoryList() {
            
            dateStr = dict[JKStoryDateKey] as! String
            latestStoryDicts = dict[JKStoryListDictKey] as! [[String : AnyObject]]
            
            if let newsListModels = [JKNewsListModel].deserialize(from: latestStoryDicts) {
                
                storieModels = newsListModels as! [JKNewsListModel]
                
                resultDict[JKStoryListModelKey] = storieModels as AnyObject
            }
            
            // 仅在网络不可用时才真正加载本地数据，因为首页数据会一直变化
            if (JKSQLiteManager.shared.reach.currentReachabilityStatus() == NotReachable) {
                
                finishedBlock([JKStoryDateKey : dateStr, JKStoryListModelKey : storieModels], nil)
                
                JKProgressHUD.showError(withStatus: "您的网络貌似有点问题~~")
                
                return
            }
        }
        
        
        // 从网络加载最新数据
        JKNetworkingTool.shared.requestGet(url: "news/latest", parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                finishedBlock(nil, error)
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到数据"))
                
                return
            }
            
            var dict = [String : AnyObject]()
            
            guard let date = (json["date"]) as? String else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到日期数据"))
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到最新文章数据"))
                
                return
            }
            
            // 缓存最新文章列表
            JKSQLiteManager.cacheStoryLists(stories: stories, date: date, isTop: false, isLatest: true, isMore: false)
            
            guard let top_stories = (json["top_stories"]) as? [[String : AnyObject]] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到热门文章数据"))
                
                return
            }
            
            // 缓存5条热门列表
            JKSQLiteManager.cacheTopStories(topStories: top_stories, date: date)
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                finishedBlock(nil, JKBaseError(desc: "最新文章转模型失败"))
                
                return
            }
            
            // 日期
            dict[JKStoryDateKey] = date as AnyObject
            
            var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: date + "000101"), format: "MM月dd日")
            fmtDate += " "
            fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: date))
            
            dict[JKStoryFmtDateKey] = fmtDate as AnyObject
            
            // 最新文章列表
            dict[JKStoryListModelKey] = newsListModels as AnyObject
            
            // 5条热门文章
            dict[JKTopStoryListKey] = top_stories as AnyObject
            /*
             if let top_storyModels = [JKNewsListModel].deserialize(from: top_stories) {
             
             dict[JKTopStoryListKey] = top_storyModels as AnyObject
             } */
            
            finishedBlock(dict as NSDictionary, nil)
        }
    }
    
    /** 加载首页更多数据 */
    public class func loadMoreOtherThemeDataWithDate(date: String, finishedBlock: @escaping ((_ dict: NSDictionary?, _ error: Error?) -> ())) {
        
        let beforeDate = JKDateTool.getPreviousDayOfSpecifiedDate(date: date)
        
        if let listsDict = JKSQLiteManager.queryStoryListWithDate(date: beforeDate) {
            
            let lists = listsDict[JKStoryListDictKey] as! [[String : AnyObject]]
            let dateStr = listsDict[JKStoryDateKey] as! String
            
            if let newsListModels = [JKNewsListModel].deserialize(from: lists) {
                
                var resultDict = [String : AnyObject]()
                
                resultDict[JKStoryDateKey] = dateStr as AnyObject
                
                resultDict[JKStoryListModelKey] = newsListModels as AnyObject
                
                var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: dateStr + "000101"), format: "MM月dd日")
                fmtDate += " "
                fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: dateStr))
                
                resultDict[JKStoryFmtDateKey] = fmtDate as AnyObject
                
                if (lists.count > 1) {
                    
                    finishedBlock(resultDict as NSDictionary, nil)
                    
                    return
                }
            }
        }
        
        // 数据库没有取得数据，从网络请求数据
        JKNetworkingTool.shared.requestGet(url: "news/before/" + date, parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                finishedBlock(nil, error)
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到数据"))
                
                return
            }
            
            var dict = [String : AnyObject]()
            
            guard let date = (json["date"]) as? String else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到日期数据"))
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                finishedBlock(nil, JKBaseError(desc: "未获取到文章数据"))
                
                return
            }
            
            // 执行缓存
            JKSQLiteManager.cacheStoryLists(stories: stories, date: date, isTop: false, isLatest: false, isMore: true)
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                finishedBlock(nil, JKBaseError(desc: "文章转模型失败"))
                
                return
            }
            
            // 日期
            dict[JKStoryDateKey] = date as AnyObject
            
            var fmtDate = JKDateTool.timeStrWithTimeStamp(timestamp: JKDateTool.getTimeStampWithFormattedStr(formattedStr: date + "000101"), format: "MM月dd日")
            fmtDate += " "
            fmtDate += (JKDateTool.getWeekdayOfSpecifiedDate(date: date))
            
            dict[JKStoryFmtDateKey] = fmtDate as AnyObject
            
            dict[JKStoryListModelKey] = newsListModels as AnyObject
            
            dict[JKStoryListDictKey] = stories as AnyObject
            
            finishedBlock(dict as NSDictionary, nil)
        }
    }
}
